package com.gonsin.gview.example.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Date;

@Api(tags = "通用接口")
@Controller
public class DownloadController {

    @ApiOperation(value = "下载 - 下载文件", hidden = true)
    @GetMapping("/restapi/s08/download")
    public ResponseEntity<FileSystemResource> getFile(
            @ApiIgnore HttpServletResponse response,
            @ApiParam("原来的下载路径") @RequestParam("url") String url) throws FileNotFoundException {

//        String path = localFileService.getPathFromUrl(url);
//        if(path == null){
//            response.setStatus(404);
//            return null;
//        }

        File file = new File("D:\\files\\0bBg2siUdNtWL8CdHBg1Pz03l7a6cEoQ.jpg");
        if (file.exists()) {
            return export(file);
        }
        return null;
    }

    public ResponseEntity<FileSystemResource> export(File file) {
        if (file == null) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + file.getName());
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));
        return ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(MediaType.parseMediaType("application/octet-stream")).body(new FileSystemResource(file));
    }

}
